#ifndef CODE_EDITOR_H
#define CODE_EDITOR_H

#include <QPlainTextEdit>
#include <QSyntaxHighlighter>
#include <QFileInfo>

class LineNumberArea;

class CodeEditor : public QPlainTextEdit {
    Q_OBJECT
    
public:
    explicit CodeEditor(QWidget *parent = nullptr);
    ~CodeEditor();
    
    void loadFile(const QString &fileName);
    bool save();
    bool saveAs();
    QString currentFile() const { return fileName; }
    
    void lineNumberAreaPaintEvent(QPaintEvent *event);
    int lineNumberAreaWidth();
    
signals:
    void fileNameChanged(const QString &fileName);
    
protected:
    void resizeEvent(QResizeEvent *event) override;
    
private slots:
    void updateLineNumberAreaWidth(int newBlockCount);
    void highlightCurrentLine();
    void updateLineNumberArea(const QRect &rect, int dy);
    
private:
    void setupEditor();
    bool maybeSave();
    
    QString fileName;
    LineNumberArea *lineNumberArea;
    QSyntaxHighlighter *highlighter;

private:
    // 添加以下成员
    QCompleter *completer;
    CodeCompleter *codeCompleter;
    QString textUnderCursor() const;
    
private slots:
    void insertCompletion(const QString &completion);
};

class LineNumberArea : public QWidget {
public:
    LineNumberArea(CodeEditor *editor) : QWidget(editor), codeEditor(editor) {}
    
    QSize sizeHint() const override {
        return QSize(codeEditor->lineNumberAreaWidth(), 0);
    }
    
protected:
    void paintEvent(QPaintEvent *event) override {
        codeEditor->lineNumberAreaPaintEvent(event);
    }
    
private:
    CodeEditor *codeEditor;
};
class CompletionPopup : public QListView {
    Q_OBJECT
public:
    CompletionPopup(QWidget *parent = nullptr);
    void keyPressEvent(QKeyEvent *e) override;
};
#endif // CODE_EDITOR_H